//
//  CityCommunityViewController.m
//  cityStar
//
//  Created by wangjia on 14/12/13.
//  Copyright (c) 2014年 tiny. All rights reserved.
//

#import "CityCommunityViewController.h"
#import "INTULocationManager.h"
#import "Define.h"
#import "HTDefine.h"
#import "PulsingHaloLayer.h"

#import "CityCommunityListViewController.h"
#import "CityForumViewController.h"
#import "BMapKit.h"
#import "CityForumViewController.h"
#import "linkModel.h"
#import "UIImageView+WebCache.h"
#import "WaresDetailViewController.h"
#import "RepairAndHomeViewController.h"
#import "LoginCityStarViewViewController.h"

@interface CityCommunityViewController ()<BMKLocationServiceDelegate>
{
    BMKLocationService *_locService;
}
@property (nonatomic,weak) IBOutlet UILabel *labelAddress;
@property (nonatomic,weak) IBOutlet UIButton *btnreFreshAddress;
@property (nonatomic,weak) IBOutlet UIButton *btnCenter;
@property (strong, nonatomic) PulsingHaloLayer *haloLayer;
@property (weak, nonatomic) IBOutlet UIButton *imagbtn;

/**
 *  左上角为第一个
 */
@property (nonatomic,weak) IBOutlet UIButton *btn01;
@property (nonatomic,weak) IBOutlet UIButton *btn02;
@property (nonatomic,weak) IBOutlet UIButton *btn03;
@property (nonatomic,weak) IBOutlet UIButton *btn04;
@property (nonatomic,weak) IBOutlet UIButton *btn05;
@property (nonatomic,weak) IBOutlet UIButton *btn06;
@property (nonatomic,weak) IBOutlet UIButton *btn07;
@property (nonatomic,weak) IBOutlet UIButton *btn08;

@property (nonatomic,weak) IBOutlet UILabel *label01;
@property (nonatomic,weak) IBOutlet UILabel *label02;
@property (nonatomic,weak) IBOutlet UILabel *label03;
@property (nonatomic,weak) IBOutlet UILabel *label04;
@property (nonatomic,weak) IBOutlet UILabel *label05;
@property (nonatomic,weak) IBOutlet UILabel *label06;
@property (nonatomic,weak) IBOutlet UILabel *label07;
@property (nonatomic,weak) IBOutlet UILabel *label08;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,weak) IBOutlet UIView *locationView;
@property (nonatomic,strong) linkModel *linkmodel;


@end

@implementation CityCommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSData *imageData = [defaults dataForKey:@"defaultImage"];
    UIImage *backGroundImage = [UIImage imageWithData:imageData];
    if (backGroundImage) {
        self.view.backgroundColor =[UIColor colorWithPatternImage:backGroundImage];
    }else{
        self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"xingkong"]];
    }
    [defaults synchronize];
    self.navigationItem.title = @"城市社区";
    
    UIButton * regBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 28)];
    regBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    regBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [regBtn setTitle:@"社区论坛" forState:UIControlStateNormal];
    [regBtn setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
    [regBtn setTitleColor:[UIColor colorWithRed:0.991 green:0.532 blue:0.303 alpha:1.000] forState:UIControlStateHighlighted];
    [regBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * iHaveNewsBtnItem = [[UIBarButtonItem alloc]initWithCustomView:regBtn];
    self.navigationItem.rightBarButtonItem = iHaveNewsBtnItem;
    
    // Do any additional setup after loading the view.
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 90, 30)];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setFrame:CGRectMake(-30, 0, 90, 30)];
    [leftButton setTitle:@"返回" forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [leftButton setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor colorWithRed:0.991 green:0.532 blue:0.303 alpha:1.000] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"back_touch"] forState:UIControlStateHighlighted];
    
    [view addSubview:leftButton];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = barButtonItem;
    
    [self setUpViews];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.7f target:self selector:@selector(showLocationAnimation) userInfo:nil repeats:YES];

    [self getAddressOfCityStar];
    [self getBMapLocation];
    [self webRequest_GetADMessage];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self.timer invalidate];
}

-(void)searchAction
{
    NSData *userData = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalDetail];
    PersonalDetail *user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    if (user.nickname) {
        CityForumViewController *cityforumVC = [[CityForumViewController alloc]init];
        [self.navigationController pushViewController:cityforumVC animated:YES];
    }else{
        [self presentLoginViewController];
    }
}
#pragma mark - IsJumpToLoginViewController
-(void)presentLoginViewController
{
    LoginCityStarViewViewController *loginCityStarVC = [[LoginCityStarViewViewController alloc]init];
    BaseNavController *baseloginNav = [[BaseNavController alloc] initWithRootViewController:loginCityStarVC];
    [self presentViewController:baseloginNav animated:YES completion:^{
    }];
}


-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewDidAppear:(BOOL)animated
{
//    if (!self.haloLayer) {
//        self.haloLayer = [PulsingHaloLayer layer];
//        self.haloLayer.radius = 100;
//        self.haloLayer.animationDuration = 2.0f;
//        self.haloLayer.backgroundColor = [UIColor whiteColor].CGColor;
//        self.haloLayer.position = self.btnCenter.center;
//        DLog(@"%@",NSStringFromCGRect(self.btnCenter.frame));
//        [self.view.layer insertSublayer:self.haloLayer below:self.btnCenter.layer];
//    }
}

#pragma mark - WebRequest
-(void)webRequest_GetADMessage
{
    
    INTULocationManager *locMgr = [INTULocationManager sharedInstance];

    NSString *postUrl = [NSString stringWithFormat:@"%@%f/y/%f",KinterFace_RegionLink,locMgr.currentLocation.coordinate.longitude,locMgr.currentLocation.coordinate.latitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSMutableArray *array = response[@"value"];
            if(array.count > 0)
            {
                self.linkmodel = [linkModel objectFromDictionary:array[0]];
                NSString * imagePath = [NSString stringWithFormat:@"%@",self.linkmodel.image];
                UIImageView *imagees = [[UIImageView alloc]init];
                [imagees sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.icszx.com/image/c/id/%@/w/182/h/132/m/0",imagePath]] placeholderImage:[UIImage imageNamed:@"品牌列表_主图"]];
                [self.imagbtn setBackgroundImage:imagees.image forState:UIControlStateNormal];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}
- (IBAction)image_Action:(id)sender {
    NSString *strType = [NSString stringWithFormat:@"%@",self.linkmodel.type];
    NSString *strId = [NSString stringWithFormat:@"%@",self.linkmodel.object_id];
    if([strType isEqualToString:@"0"])
    {
        WaresDetailViewController *wareVC = [[WaresDetailViewController alloc]initWithCommodityID:strId];
        [self.navigationController pushViewController:wareVC animated:YES];
    }else if([strType isEqualToString:@"1"]){
        RepairAndHomeViewController *repairVC = [[RepairAndHomeViewController alloc]initWithMerchantID:strId];
        [self.navigationController pushViewController:repairVC animated:YES];
    }
}

-(void)showLocationAnimation
{
//    CGPoint touchPoint=[[touches anyObject]locationInView:self.view];
    CALayer *waveLayer=[CALayer layer];
    waveLayer.frame = CGRectMake(self.btnCenter.x+self.btnCenter.width/2-5, self.btnCenter.y+self.btnCenter.height/2-5, 10, 10);
    waveLayer.borderColor =[UIColor colorWithWhite:1.000 alpha:0.600].CGColor;
    waveLayer.borderWidth =0.1;
    waveLayer.cornerRadius =5.0;
    
    [self.locationView.layer addSublayer:waveLayer];
    [self scaleBegin:waveLayer];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//    CGPoint touchPoint=[[touches anyObject]locationInView:self.view];
//    CALayer *waveLayer=[CALayer layer];
//    waveLayer.frame = CGRectMake(self.btnCenter.x+self.btnCenter.width/2, self.btnCenter.y+self.btnCenter.height/2, 10, 10);
//    waveLayer.borderColor =[UIColor whiteColor].CGColor;
//    waveLayer.borderWidth =0.5;
//    waveLayer.cornerRadius =5.0;
//    
//    [self.view.layer addSublayer:waveLayer];
//    [self scaleBegin:waveLayer];
}

-(void)scaleBegin:(CALayer *)aLayer
{
    const float maxScale=120.0;
    if (aLayer.transform.m11<maxScale) {
        if (aLayer.transform.m11==1.0) {
            [aLayer setTransform:CATransform3DMakeScale( 1.1, 1.1, 1.0)];
            
        }else{
            [aLayer setTransform:CATransform3DScale(aLayer.transform, 1.1, 1.1, 1.0)];
        }
        [self performSelector:_cmd withObject:aLayer afterDelay:0.08];
    }else [aLayer removeFromSuperlayer];
}

-(void)viewWillAppear:(BOOL)animated
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0) {
        self.navigationController.navigationBar.translucent = NO; //禁止半透明毛玻璃效果
        self.navigationController.navigationBar.tintColor = kWhiteNavTitleColor; //返回按钮颜色
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor]; //bar背景颜色
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]}; //标题颜色
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }else{
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]]; //bar背景颜色
        self.navigationController.navigationBar.translucent = NO;
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]};
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }
}

-(void)setUpViews
{
    self.btn01.hidden = YES;
    self.btn02.hidden = YES;
    self.btn03.hidden = YES;
    self.btn04.hidden = YES;
    self.btn05.hidden = YES;
    self.btn06.hidden = YES;
    self.btn07.hidden = YES;
    self.btn08.hidden = YES;
    
    self.label01.hidden = YES;
    self.label02.hidden = YES;
    self.label03.hidden = YES;
    self.label04.hidden = YES;
    self.label05.hidden = YES;
    self.label06.hidden = YES;
    self.label07.hidden = YES;
    self.label08.hidden = YES;
}

-(IBAction)sendidbtn:(UIButton *)sender
{
    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
    float y = currentLocation.coordinate.latitude;
    float x = currentLocation.coordinate.longitude;
    CityCommunityListViewController *cityListVC = [[CityCommunityListViewController alloc]init];
    cityListVC.xlatitude = x;
    cityListVC.ylongitude = y;
    cityListVC.type = sender.tag;
    [self.navigationController pushViewController:cityListVC animated:YES];
}

#pragma mark - Action

-(void)getBMapLocation
{
    //设置定位精确度，默认：kCLLocationAccuracyBest
//    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
//    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
//    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
//    [_locService startUserLocationService];
}

-(void)getAddressOfCityStar
{
    static BOOL firstFailed = YES;
    INTULocationManager *locMgr = [INTULocationManager sharedInstance];
    [locMgr requestLocationWithDesiredAccuracy:INTULocationAccuracyCity timeout:1 delayUntilAuthorized:YES block:^(CLLocation *currentLocation, INTULocationAccuracy INTULocationAccuracyBlock, INTULocationStatus status) {
        
        //TODO:网络请求,有几家机构
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (status == INTULocationStatusSuccess||status == INTULocationStatusTimedOut||currentLocation) {
            
            CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
            CLGeocodeCompletionHandler handle = ^(NSArray *placemarks,NSError *error)
            {
                for (CLPlacemark * placeMark in placemarks)
                {
                    //比如：滨江区
                    NSDictionary *addressDic = placeMark.addressDictionary;
//                    DLog(@"%@",addressDic);
//                    NSString *subLocality = addressDic[@"SubLocality"];
                    NSString *cityName = addressDic[@"Name"];
                    self.labelAddress.text = cityName;
//                    CATransition *transition = [CATransition animation];
//                    transition.duration = 1.0f;
//                    transition.type = @"rippleEffect";
//                    transition.subtype = kCATransitionMoveIn;
//                    [self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
//                    [self.view.layer addAnimation:transition forKey:@"animation"];
                    self.btn01.hidden = NO;
                    self.btn02.hidden = NO;
                    self.btn03.hidden = NO;
                    self.btn04.hidden = NO;
                    self.btn05.hidden = NO;
                    self.btn06.hidden = NO;
                    self.btn07.hidden = NO;
                    self.btn08.hidden = NO;
                    
                    self.label01.hidden = NO;
                    self.label02.hidden = NO;
                    self.label03.hidden = NO;
                    self.label04.hidden = NO;
                    self.label05.hidden = NO;
                    self.label06.hidden = NO;
                    self.label07.hidden = NO;
                    self.label08.hidden = NO;
                    //                        strongSelf.currentlocation_Lbl.text = subLocality.length>0?subLocality:city;
                    //                        locMgr.currentCity = city;
                    //                        strongSelf.hasGetLocation = YES;
                    return ;
                }
            };
            [clGeoCoder reverseGeocodeLocation:currentLocation completionHandler:handle];
            
        }else{
            if (status == INTULocationStatusError) {
                //                    strongSelf.currentlocation_Lbl.text = @"定位失败";
            }else{
                //定位失败，可能未获得权限
                if (firstFailed) {
                    //                        FastAlertViewWithTitle(@"请允许求学记获得定位权限，才可能获取周边机构...");
                    firstFailed = NO;
                }
                //                    strongSelf.currentlocation_Lbl.text = @"请开启定位";
            }
            //                strongSelf.hasGetLocation = NO;
        }
    }];
}

-(IBAction)refreshAddress_Touch:(id)sender
{
    [self getAddressOfCityStar];
}
#pragma mark - BMKUserLocatonDelegate
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
//    NSLog(@"heading is %@",userLocation.heading);
//    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
//    DLog(@"INTUlat = %f  INTUlong = %f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);

//    DLog(@"lat = %f  long = %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
